package com.newear.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.newear.MyApplication;
import com.newear.R;
import com.newear.constant.DataType;
import com.newear.constant.RequireParams;
import com.newear.message.MessageDispatcher;
import com.newear.message.MessageType;
import com.newear.util.MyLogger;
import com.newear.util.MySharedPreferences;
import com.newear.util.ProgressDialogUtil;
import com.newear.util.T;
import com.newear.util.Validator;

import java.lang.ref.WeakReference;

public class HappyLoginActivity extends AppCompatActivity {
    private static final String TAG = "HappyLoginActivity";
    private EditText et_login_user;
    private EditText et_login_password;
    private ImageView img_login_close;
    private Button btn_login_sure;
    private Context mContext;
    private String key;
    private MyHandler myHandler;
    private ProgressDialog mProgressDialog; //网络请求时用的进度条

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.happy_login_activity);
        init();
        findViews();
        setListeners();
    }

    private void init(){
        this.mContext = this;
        this.key = this.hashCode() + "";
        myHandler = new MyHandler(this);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
    }

    private void findViews(){
        //账号输入
        et_login_user = (EditText) findViewById(R.id.et_login_user);
        et_login_user.requestFocus();
        //密码输入
        et_login_password = (EditText) findViewById(R.id.et_login_password);
        img_login_close = (ImageView) findViewById(R.id.img_login_close);
        //确定按钮
        btn_login_sure = (Button) findViewById(R.id.btn_login_sure);
    }

    private void setListeners(){
        img_login_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HappyLoginActivity.this.finish();
            }
        });

        btn_login_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = et_login_user.getText().toString().trim();
                String pwd = et_login_password.getText().toString().trim();
                if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                    login(username, pwd);
                } else {
                    T.shortToast(mContext, "用户名或密码为空，请完善！");
                }
            }
        });

    }

    /**
     * 用户登陆
     * @param username
     * @param pwd
     */
    private void login(String username,String pwd) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.DATA_TYPE, DataType.USER_LOGIN);
        param.put(RequireParams.MAP_KEY, this.key + DataType.USER_LOGIN);
        param.put(RequireParams.USER_NAME, username);
        param.put(RequireParams.PASSWORD, pwd);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final HappyLoginActivity activity = (HappyLoginActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.setMessage(activity.getResources().getString(R.string.login));
                                activity.mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.USER_LOGIN) {
                                SparseArray<String> result = (SparseArray<String>) msg.obj;
                                String errno = result.get(0);
                                if ("0".equals(errno)) {
                                    String token = MySharedPreferences.getInstance().getToken(activity);
                                    MyLogger.e(token);
                                    activity.finish();
                                } else if ("1".equals(errno)){
                                    String errMsg = result.get(1);
                                    T.shortToast(activity, errMsg);
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "handleMessage Exception!e:" + e.getMessage());
            }
        }
    }
}
